package com.xk.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.hy.common.enums.ExceptionEnums;
import com.hy.common.exception.XkException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 实现图片上传的功能
 */
@Service
@Slf4j
public class UploadService {
    @Autowired
    private FastFileStorageClient storageClient;

    private static final List<String> ALLOW_TYPES= Arrays.asList("image/jpeg","image/png","image/bmp","image/jpg");
    public String uploadImage(MultipartFile file){

        try {
            //校验文件的类型
            String contentType = file.getContentType();
            if (!ALLOW_TYPES.contains(contentType)){//拿得到的类型到集合中进行匹配，
                throw new XkException(ExceptionEnums.INVALID_FILE_TYPE);
            }
            //校验文件的内容
            BufferedImage image = ImageIO.read(file.getInputStream());

            if (image==null){//为null就不是图片,然后抛异常
                throw new XkException(ExceptionEnums.INVALID_FILE_TYPE);
            }

            String originalFilename = file.getOriginalFilename();//获得文件名
           //将文件保存到FastDFS
            //第一个参数是文件的流，第二个参数是file的大小，第三个是后缀，第四可以不传
     //originalFilename.substring(file.getOriginalFilename().lastIndexOf(".")+1);此方法截后缀效率低
            String extension= StringUtils.substringAfterLast(file.getOriginalFilename(),".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            return "http://image.xkhy.com/"+storePath.getFullPath();

        } catch (IOException e) {
            //记录日志
            log.error("上传失败文件",e);
            throw new XkException(ExceptionEnums.UPLOAD_FILE_ERROR);

        }
    }
}
